package com.projet.whattowatch.activity;

import java.util.ArrayList;

import com.projet.whattowatch.R;
import com.projet.whattowatch.adapter.HumainAdapterPlus;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class SearchPersonFragment extends Fragment
{
	private EditText keyword;
	private Button searchButton;
	private ListView searchList;
	
	final String EXTRA_HUMAIN_NAME = "humain_name";
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View rootView = inflater.inflate(R.layout.search_person_layout, container, false);
		
		keyword = (EditText) rootView.findViewById(R.id.keywordEditText);
		searchButton = (Button) rootView.findViewById(R.id.searchButton);
		searchList = (ListView) rootView.findViewById(R.id.searchListView);
		
		searchButton = (Button) rootView.findViewById(R.id.searchButton);
		searchButton.setOnClickListener(searchListener);
		
		return rootView;
	}
	
	public OnClickListener searchListener = new OnClickListener()
	{
		@Override
		public void onClick(View arg0)
		{
			String stringKeyword = keyword.getText().toString();

			ArrayList<String> result = MainActivity.mLibHumain.searchHumain(stringKeyword);
    		ArrayList<String> humainName = new ArrayList<String>();
            ArrayList<String> humainUrl = new ArrayList<String>();
    		
    		for(int i = 0; i < result.size(); i++)
    		{
    			for(int j = 0; j < MainActivity.mLibHumain.getListHumain().size(); j++)
	            {
    				if(result.get(i).equals(MainActivity.mLibHumain.getHumain(j).getPrenom() + " " + MainActivity.mLibHumain.getHumain(j).getNom()))
    				{
    	    			humainName.add(MainActivity.mLibHumain.getHumain(j).getPrenom() + " " + MainActivity.mLibHumain.getHumain(j).getNom());
    	    			humainUrl.add(MainActivity.mLibHumain.getHumain(j).getImageUrl());
    				}
	            }
    		}
    		
    		HumainAdapterPlus adapter = new HumainAdapterPlus(getActivity(), humainName, humainUrl);

			searchList.setAdapter(adapter);
			hideSoftKeyboard();
		}
	};
	
	private void hideSoftKeyboard()
    {
        if(getActivity().getCurrentFocus()!=null && getActivity().getCurrentFocus() instanceof EditText){
            InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getActivity().getWindow().getCurrentFocus().getWindowToken(), 0);
        }
    }
}